import random
from threading import Timer
from pymodbus.client import ModbusSerialClient as ModbusClient

class A8(object):
    def __init__(self,port='COM5', baudrate=9600,slave=1, devName='A8'):
        self.port = port
        self.baudrate = baudrate
        self.devName = devName
        self.address = 0
        self.count = 8
        self.slave = slave
    def read_reg(self):
        res = []
        data = []
        client = ModbusClient(port=self.port, baudrate=self.baudrate, name=self.devName)
        client.connect()
        try:
            response = client.read_input_registers(address=self.address, count=self.count, slave=self.slave)
            #response = client.read_holding_registers(address=self.address, count=self.count, slave=self.slave)
            print(response)
            res = response.registers
        except Exception as e:
            client.close()
            print(e)
            print('读数据失败，请检查端口是否被占用！')
            return data
        for i in range(len(res)):
            s = round(res[i]/149.1,2)
            data.append(s)
            #print('通道%d：%s mA' % (i+1,s))
        client.close()
        return data
    def read_random(self):
        data = []
        for i in range(8):
            data.append(random.randint(0, 100))
        return data
    def loop_func(self,func,second):
        func()
        while True:
            timer1 = Timer(second, func)
            timer1.start()
            timer1.join()
#loop_func(read_reg, 1)
if __name__ == '__main__':
    a8 = A8()
    a8.loop_func(a8.read_reg, 1)
    #print(a8.read_reg())
    #input()